import argparse
import os
import lib.encode
import lib.decode


def main():
    parser = argparse.ArgumentParser(description='dp file parser', prog='dp')
    parser.add_argument('option', choices=['create', 'parse'], help='crate: crate a dp file, parse: parse a dp file')
    parser.add_argument('files', type=str, nargs='+', help='an integer for the accumulator')
    parser.add_argument('-o', '--output', metavar='', type=str, help='output file or dir name')
    parser.add_argument('-p', '--password', metavar='', type=str, help="file password")
    args = parser.parse_args()

    if args.option == 'parse':  # 解析逻辑
        # 文件数量判断
        if len(args.files) > 1:
            parser.error("please provide only one dp file")
        file_path = os.path.join(os.getcwd(), args.files[0])
        # 文件是否存在判断
        if not os.path.exists(file_path):
            parser.error(f"The file [{args.files[0]}] is not find")
        # 开始解析
        lib.decode.Decode(file_path, outDir=args.output, password=args.password)
    elif args.option == 'create':  # 创建逻辑
        # 解析文件路径
        file_path = []
        for file in args.files:
            path = os.path.join(os.getcwd(), file)
            if os.path.exists(path):
                file_path.append(path)
            else:
                parser.error(f'The file [{file}] does not exist.')
        # 开始生成文件
        lib.encode.Encode(file_path, output_file_name=args.output, password=args.password)


if __name__ == '__main__':
    # 代码调用
    # lib.encode.Encode(filePath, output_file_name=None, password=None)
    # lib.decode.Decode("pwd123123.dp", "out3", password="123123")
    # lib.encode.Encode(filePath)
    # lib.decode.Decode("out.dp")
    # 命令行调用
    # python3 main.py create 1.txt 2.txt -p 123 -o pwd123.dp
    # python3 main.py parse pwd123.dp -p 123 -o out2
    main()
